import SockJS from 'sockjs-client';
import Stomp from 'stompjs';

class WebSocketClient {
  constructor() {
    this.stompClient = null;
    this.subscriptions = {};
    this.reconnectAttempts = 0;
    this.maxReconnectAttempts = 5;
    this.reconnectDelay = 5000;
    this.isConnecting = false;
  }

  connect(token, onConnect, onError) {
    if (this.stompClient && this.stompClient.connected) {
      return;
    }

    if (this.isConnecting) {
      console.log('WebSocket connection already in progress');
      return;
    }

    this.isConnecting = true;

    // 构建SockJS URL (不含token)
    const socketUrl = `${window.location.protocol === 'https:' ? 'https:' : 'http:'}//${window.location.hostname}${process.env.NODE_ENV === 'development' ? ':8080' : ''}/ws`;
    
    console.log('Attempting to connect to WebSocket:', socketUrl);
    
    // 使用SockJS创建WebSocket连接
    const socket = new SockJS(socketUrl);
    this.stompClient = Stomp.over(socket);
    this.stompClient.debug = null;

    this.stompClient.connect(
      {
        'Authorization': `Bearer ${token}`,
        'X-Requested-With': 'XMLHttpRequest'
      },
      (frame) => {
        this.isConnecting = false;
        this.reconnectAttempts = 0;
        console.log('WebSocket connected:', frame);
        if (onConnect) onConnect(frame);
      },
      (error) => {
        this.isConnecting = false;
        console.error('WebSocket connection error:', error);
        if (onError) onError(error);
        this.reconnect(token, onConnect, onError);
      }
    );
  }

  isConnected() {
    return this.stompClient && this.stompClient.connected;
  }

  reconnect(token, onConnect, onError) {
    if (this.reconnectAttempts < this.maxReconnectAttempts) {
      this.reconnectAttempts++;
      console.log(`Attempting to reconnect (${this.reconnectAttempts}/${this.maxReconnectAttempts})...`);
      setTimeout(() => {
        if (!this.isConnected()) {
          this.connect(token, onConnect, onError);
        } else {
          console.log('WebSocket already reconnected');
        }
      }, this.reconnectDelay);
    } else {
      console.error('Max reconnection attempts reached. Please refresh the page or try again later.');
    }
  }

  subscribe(destination, callback) {
    if (this.stompClient && this.stompClient.connected) {
      const subscription = this.stompClient.subscribe(destination, (message) => {
        try {
          callback(JSON.parse(message.body));
        } catch (e) {
          console.error('Failed to parse message:', e);
        }
      });
      this.subscriptions[destination] = subscription;
      return subscription;
    }
    return null;
  }

  unsubscribe(destination) {
    if (this.subscriptions[destination]) {
      this.subscriptions[destination].unsubscribe();
      delete this.subscriptions[destination];
    }
  }

  send(destination, headers = {}, body = {}) {
    if (this.stompClient && this.stompClient.connected) {
      this.stompClient.send(destination, headers, JSON.stringify(body));
      return true;
    }
    return false;
  }

  disconnect() {
    if (this.stompClient) {
      Object.keys(this.subscriptions).forEach(dest => this.unsubscribe(dest));
      this.stompClient.disconnect();
      this.stompClient = null;
    }
  }
}

export default new WebSocketClient();